package com.itcast.trade.bulls.stock.user.controller;

import com.itcast.bulls.stock.common.exception.ComponentException;
import com.itcast.bulls.stock.common.exception.constants.ApplicationErrorCodeEnum;
import com.itcast.bulls.stock.common.utils.GlobalConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class BaseController {

    /**
     * token的存取管理接口
     */
    @Autowired
    private TokenStore tokenStore;

    /**
     * 获取当前请求的token信息
     * @return
     */
    protected  String getCurrentToken() {
        // 1. 获取Request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 2. 获取token信息
        String token = request.getHeader("Authorization");
        if(null != token) {
            token = token.replace(OAuth2AccessToken.BEARER_TYPE, "").trim();
        }
        return token ;
    }

    /**
     * 获取用户增强信息
     * @return
     * @throws ComponentException
     */
    protected  Map<String, Object> getUserAdditionalInfos()  throws ComponentException {
        //1. 获取Access Token 信息
        OAuth2AccessToken auth2AccessToken = tokenStore.readAccessToken(getCurrentToken());
        if(null == auth2AccessToken) {
            throw new ComponentException(ApplicationErrorCodeEnum.SYS_NOT_VALID_TOKEN);
        }

        // 2. 获取token的增强信息
        Map<String, Object> additionalInfos = auth2AccessToken.getAdditionalInformation();
        if(null == additionalInfos) {
            throw new ComponentException(ApplicationErrorCodeEnum.SYS_NOT_ACCESS_USER);
        }
        return additionalInfos;
    }


}
